<template>
  <div class="card">
    <h2 class="text-lg font-bold">社会消费品零售总额</h2>
    <div class="chart-container bg-white rounded-lg shadow p-2 pb-5">
      <LineChart :data="retailChartData" :options="retailChartOptions" class="w-full h-48" />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 预测函数 - 使用线性回归算法
const predictValue = (historicalData) => {
  const actualData = historicalData.filter((value) => value !== null)
  const n = actualData.length

  if (n < 2) return null

  let sumX = 0
  let sumY = 0
  let sumXY = 0
  let sumX2 = 0

  for (let i = 0; i < n; i++) {
    const x = i + 1
    const y = actualData[i]
    sumX += x
    sumY += y
    sumXY += x * y
    sumX2 += x * x
  }

  const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX)
  const intercept = (sumY - slope * sumX) / n
  return slope * (n + 1) + intercept
}

// 初始化图表数据（包含预测值）
const initChartData = () => {
  const retailData = [945.8, 962.83, 1032.02, 1033.05]
  const growthData = [10.1, 2.3, 7.2, 1.2]

  const retailForecast = predictValue(retailData).toFixed(2)
  const growthForecast = predictValue(growthData).toFixed(2)

  return {
    labels: ['2021年', '2022年', '2023年', '2024年', '2025年(预测)'],
    datasets: [
      {
        label: '社会消费品零售总额',
        data: [...retailData, Number(retailForecast)],
        backgroundColor: (context) =>
          context.dataIndex === 4 ? 'rgba(255, 206, 86, 0.4)' : 'rgba(255, 206, 86, 0.8)',
        borderColor: (context) =>
          context.dataIndex === 4 ? 'rgba(255, 206, 86, 0.6)' : 'rgba(255, 206, 86, 1)',
        borderWidth: 1,
        type: 'bar',
        borderRadius: 4,
        barPercentage: 0.6,
        categoryPercentage: 0.7,
      },
      {
        label: '增速(%)',
        data: [...growthData, Number(growthForecast)],
        backgroundColor: 'rgba(75, 192, 192, 0.8)',
        borderColor: (context) =>
          context.dataIndex === 4 ? 'rgba(75, 192, 192, 0.6)' : 'rgba(75, 192, 192, 1)',
        borderWidth: 2,
        borderDash: (context) => (context.dataIndex === 4 ? [5, 5] : []),
        type: 'line',
        fill: false,
        tension: 0.3,
        pointRadius: (context) => (context.dataIndex === 4 ? 6 : 4),
        pointBackgroundColor: (context) =>
          context.dataIndex === 4 ? 'rgba(75, 192, 192, 0.6)' : '#fff',
        pointBorderColor: 'rgba(75, 192, 192, 1)',
        pointBorderWidth: 2,
        yAxisID: 'y1',
      },
    ],
  }
}

// 社会消费品零售总额图表数据
const retailChartData = ref(initChartData())

const retailChartOptions = ref({
  responsive: true,
  maintainAspectRatio: false,
  interaction: {
    mode: 'index',
    intersect: false,
  },
  scales: {
    x: {
      grid: { display: false },
      ticks: {
        color: '#666',
        maxRotation: 0, // 确保x轴标签不倾斜
        minRotation: 0,
        autoSkip: false,
        maxTicksLimit: 5, // 限制最大刻度数
      },
    },
    y: {
      beginAtZero: true,
      grid: { color: 'rgba(0, 0, 0, 0.05)' },
      ticks: {
        color: '#666',
        callback: (value) => value + '亿',
      },
    },
    y1: {
      beginAtZero: true,
      position: 'right',
      grid: {
        color: 'rgba(0, 0, 0, 0.05)',
        drawOnChartArea: false,
      },
      ticks: {
        color: '#666',
        callback: (value) => value + '%',
      },
    },
  },
  plugins: {
    legend: {
      labels: { color: '#333' },
    },
    tooltip: {
      mode: 'index',
      intersect: false,
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      titleColor: '#333',
      bodyColor: '#666',
      borderColor: 'rgba(200, 200, 200, 1)',
      borderWidth: 1,
      padding: 10,
      boxPadding: 5,
      usePointStyle: true,
      callbacks: {
        label: (context) => {
          let label = context.dataset.label || ''
          if (label) label += ': '
          if (context.parsed.y !== null) {
            const value = context.dataset.label.includes('增速')
              ? context.parsed.y.toFixed(1)
              : context.parsed.y.toFixed(2)
            label += value + (context.dataset.label.includes('增速') ? '%' : '亿')
            if (context.dataIndex === 4) {
              label += ' (预测)'
            }
          }
          return label
        },
      },
    },
  },
})
</script>

<style scoped>
.chart-container {
  height: 200px;
}
</style>
